<?php
/**
* Copyright 2009 Waag Society <http://www.waag.org>
* This file is part of Annotrax.
*
* Annotrax is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License,
* or (at your option) any later version.
*
* Annotrax is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Annotrax.
* If not, see http://www.gnu.org/licenses/gpl.html
*/

class Default_Model_ChannelMapper extends At_Model_Mapper{
    protected $dbTable;
    protected $tableName = 'channel';

    public function fetchAll( Default_Model_Channel $channel ){
		if( null !== $channel->getMovie() ){
			$query = '
				SELECT c.*
				FROM channel_movie cm
 				LEFT JOIN channel c ON c.id = cm.channel_id
				WHERE cm.movie_id = ?
			';

			$result = $this->getTable()->getAdapter()->fetchAll( $query, $channel->getMovie()->id );
		}
		else{
			$result = $this->getTable()->fetchAll();
		}

		$collect = array();
		foreach( $result as $values ){
			if( ! is_array( $values ) ) $values = $values->toArray();
			$collect[] = new Default_Model_Channel( $values );
		}

		return $collect;
    }

    public function save( Default_Model_Channel $channel ){
		$db = $this->getTable()->getAdapter();

        $values = array(
            'name'      	=> $channel->name,
            'description'  	=> $channel->description,
			'type'			=> $channel->type
        );

		if( null == $channel->id ){
			$channel->id = $this->getTable()->insert( $values );
		}
		else{
            $this->getTable()->update($values, array('id = ?' => $channel->id));
		}

		if( ($keywords = $channel->getKeywords() ) && null !== $keywords && count( $keywords ) > 0 ){
			$db->delete('channel_keyword', sprintf('channel_id = %d', $channel->id));
			foreach( $keywords as $keyword ){
				$db->insert( 'channel_keyword', array('channel_id' => $channel->id, 'keyword_id' => $keyword->id));
			}
		}
		else{
			$db->delete('channel_keyword', sprintf('channel_id = %d', $channel->id));
		}

        return $channel;
	}

	public function delete( Default_Model_Channel $channel ){
		$db = $this->getTable()->getAdapter();

		$db->delete('annotation', sprintf( 'channel_id = %d', $channel->id ) );
		$db->delete('channel_keyword', sprintf( 'channel_id = %d', $channel->id ) );
		$db->delete('channel_movie', sprintf( 'channel_id = %d', $channel->id ) );
		$db->delete('channel', sprintf( 'id = %d', $channel->id ) );
	}
}
